<template>
  <div class="l-upload">
    <view class="pro-flex">
      <view class="pro-img">
        <view class="title" v-if="title !== ''">{{ title }}</view>
        <view class="_df _ac _fr">
          <view class="image-list _df _ac _fr">
            <template v-for="(img, index) in proImgs">
              <view @tap="ViewImage(index)" :key="index" class="img mr10 mb10">
                <u-icon
                  size="40"
                  class="icon"
                  @tap.stop="delImg(img, index)"
                  :color="themeColor"
                  name="minus-circle"
                ></u-icon>
                <image :src="img" mode="" />
              </view>
            </template>
          </view>
          <view
            @click="chooseImg"
            v-if="proImgs.length < count"
            class="image-upload _df _ac _fc _jc"
          >
            <u-icon name="photo" size="60"></u-icon>
            选择图片
          </view>
        </view>
      </view>
    </view>
  </div>
</template>

<script>
import host from "@/utils/config";
import themes from '@/utils/theme.js'
export default {
  name: "l-upload",
  props: {
    // 标题
    imgTitle: String,
    // 上传数
    maxCount: {
      type: Number,
      default: 1,
    },
    // 已上传图片
    imgUrl: Array,
    // 上传api
    uploadApi: String,
  },
  data() {
    return {
      title: "上传图片",
      count: 1,
      proImgs: [],
      imgApi: "",
      themeColor:themes.themeColor,
    };
  },
  computed: {},
  methods: {
    // 选择图片
    chooseImg() {
      let that = this;
      uni.chooseImage({
        count: this.count, // 最多可以选择的图片张数，默认9
        sizeType: ["compressed"], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ["album", "camera"], // album 从相册选图，camera 使用相机，默认二者都有
        success: function (res) {
          //上传图片大小限制
          if (res.tempFiles[0].size > 10 * 1024 * 1024) {
            //上传图片大小限制
            that.$u.toast("图片大小不能超过10M", 2000);
            return;
          }
          uni.showLoading({
            title: "上传中...",
          });
          // 将多选照片一张一张上传
          // 注意：如果原本就有图片的情况下，只能上传剩余数量的图片
          let num = that.proImgs.length + res.tempFiles.length
          if (num <= that.count) {
            res.tempFiles.map((item) => {
              that.uploadAvatar(item);
            });
          }else{
            that.$u.toast("最多只能传"+that.count +"张", 2000);
          }
        },
      });
    },
    uploadAvatar(file) {
      let that = this;
      let param = {
        file: file,
      };
      let withToken = {
        "Content-Type": "application/json; charset=utf-8",
        Authorization: "Bearer " + uni.$_getToken(),
      };
      let url = that.hosts + this.imgApi;
      uni.uploadFile({
        url: url,
        filePath: file.path,
        name: "file",
        header: withToken,
        formData: param,
        success: (res) => {
          if (res.data) {
            let data = JSON.parse(res.data);
            that.proImgs.push(data.data.fileUrl);
          }
          uni.hideLoading();
        },
      });
    },
    //预览图片
    ViewImage(current) {
      uni.previewImage({
        urls: this.proImgs,
        loop: true,
        current: current,
      });
    },
    // 删除图片
    delImg(e, index) {
      let that = this;
      uni.showModal({
        title: "提示",
        content: "确定要删除照片吗？",
        cancelText: "取消",
        confirmText: "确定",
        success: (res) => {
          if (res.confirm) {
            that.proImgs.splice(index, 1);
            that.$emit("imgList", that.proImgs);
          }
        },
      });
    },
  },
  watch: {
    imgTitle(v) {
      this.title = v;
    },
    imgUrl: {
      handler(newVal) {
        this.proImgs = newVal;
      },
      deep: true,
    },
    maxCount(v) {
      this.count = v;
    },

    uploadApi(v) {
      this.imgApi = v;
    },
  },

  // 组件周期函数--监听组件挂载完毕
  mounted() {
    this.hosts = host.host1;
    this.imgApi = this.uploadApi;
    this.proImgs = this.imgUrl;
    this.count = this.maxCount;
    this.title = this.imgTitle;
  },
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
};
</script>

<style lang="scss" scoped>
.l-upload {
  background: #fff;
  width: 100%;
  .pro-flex {
    .pro-img {
      .title {
        padding-bottom: 30rpx;
        font-size: $uni-font-size-30;
        color: #6e6e6e;
      }
      .image-upload {
        width: 200rpx;
        height: 200rpx;
        background: #f4f5f6;
        color: #9a9c9d;
      }
      .image-list {
        .img {
          width: 200rpx;
          height: 200rpx;
          position: relative;
          z-index: 20;
          .icon {
            position: absolute;
            top: -5rpx;
            right: -5rpx;
          }
          image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
}
</style>